<template>
  <!-- 分配角色对话框 -->
  <el-dialog 
    v-model="visible" 
    title="分配角色" 
    width="500px"
    :close-on-click-modal="false"
    class="assign-role-dialog"
    @close="handleClose"
  >
    <el-form 
      ref="userAssignRoleRef" 
      :model="userAssignRole" 
      label-position="top"
      class="role-form"
    >
      <el-form-item label="用户名">
        <el-input 
          v-model="userAssignRole.userCode" 
          disabled
          prefix-icon="User"
        >
          <template #append>
            <el-tag size="small" type="info">不可修改</el-tag>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="角色">
        <div class="role-selection">
          <el-checkbox-group 
            v-model="userAssignRole.roleCheckList"
            class="role-checkbox-group"
          >
            <el-checkbox 
              v-for="role of userAssignRole.roleList" 
              :key="role.roleId"
              :label="role.roleName"
              class="role-checkbox"
            >
              <div class="role-info">
                <span class="role-name">{{ role.roleName }}</span>
                <el-tag 
                  size="small" 
                  :type="getRoleTagType(role.roleName)"
                  class="role-tag"
                >
                  {{ getRoleType(role.roleName) }}
                </el-tag>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="assignRole"
          :loading="loading"
          :disabled="!hasChanges"
        >
          {{ loading ? '保存中...' : '确认修改' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { get, put, tip } from "@/common";
import { User } from '@element-plus/icons-vue'

const visible = ref(false);
const loading = ref(false);
const userRoleList = ref([]);
const originalRoles = ref([]);

// 分配角色对象
const userAssignRole = reactive({
  userId: '',
  userCode: '',
  roleList: [],
  roleCheckList: []
});

// 检查是否有变更
const hasChanges = computed(() => {
  if (!originalRoles.value.length) return false;
  if (originalRoles.value.length !== userAssignRole.roleCheckList.length) return true;
  return !originalRoles.value.every(role => userAssignRole.roleCheckList.includes(role));
});

// 获取角色标签类型
const getRoleTagType = (roleName) => {
  const roleTypes = {
    '超级管理员': 'danger',
    '管理员': 'warning',
    '普通用户': 'success',
    '访客': 'info'
  };
  return roleTypes[roleName] || 'info';
};

// 获取角色类型描述
const getRoleType = (roleName) => {
  const roleTypes = {
    '超级管理员': '系统级',
    '管理员': '管理级',
    '普通用户': '用户级',
    '访客': '访客级'
  };
  return roleTypes[roleName] || '自定义';
};

// 重置表单
const resetForm = () => {
  Object.assign(userAssignRole, {
    userId: '',
    userCode: '',
    roleList: [],
    roleCheckList: []
  });
  userRoleList.value = [];
  originalRoles.value = [];
};

// 关闭对话框
const handleClose = () => {
  resetForm();
  visible.value = false;
};

// 打开对话框并初始化
const open = async (user, roleList) => {
  Object.assign(userAssignRole, {
    userId: user.userId,
    userCode: user.userCode,
    roleList: roleList,
    roleCheckList: []
  });
  
  visible.value = true;
  
  try {
    const result = await get(`/user/user-role-list/${user.userId}`);
    userRoleList.value = result.data;
    checkedUserRole();
    // 保存原始角色列表用于比较
    originalRoles.value = [...userAssignRole.roleCheckList];
  } catch (error) {
    console.error('Failed to fetch user roles:', error);
    tip.error('获取用户角色失败');
    handleClose();
  }
};

// 设置用户已有角色
const checkedUserRole = () => {
  userAssignRole.roleCheckList = userRoleList.value.map(role => role.roleName);
};

const userAssignRoleRef = ref();

// 分配角色
const assignRole = async () => {
  if (!hasChanges.value) {
    tip.warning('未做任何修改');
    return;
  }

  loading.value = true;
  try {
    const result = await put(
      '/user/assignRole', 
      userAssignRole, 
      { title: "提示", message: "您确定要修改用户角色吗？" }
    );
    tip.success(result.message);
    handleClose();
  } catch (error) {
    console.error('Failed to assign roles:', error);
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<style scoped>
.assign-role-dialog {
  --el-dialog-padding-primary: 20px;
}

.role-form {
  padding: 0 20px;
}

:deep(.el-form-item__label) {
  padding-bottom: 8px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-input-group__append) {
  padding: 0 8px;
  background-color: transparent;
}

:deep(.el-tag) {
  margin: 0;
  border: none;
}

.role-selection {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 16px;
  background-color: var(--el-fill-color-blank);
}

.role-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.role-checkbox {
  margin-right: 0 !important;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.role-checkbox:hover {
  background-color: var(--el-fill-color-light);
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: var(--el-color-primary);
}

.role-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.role-name {
  font-weight: 500;
}

.role-tag {
  font-size: 12px;
}

.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-lighter);
  padding: 20px;
}

:deep(.el-button) {
  padding: 8px 20px;
  border-radius: 2px;
}
</style>